package com.scheduling.machine.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scheduling.machine.dto.MachineTypeDTO;
import com.scheduling.machine.dto.MachineTypeQueryDTO;
import com.scheduling.machine.entity.MachineType;
import com.scheduling.machine.mapper.MachineMapper;
import com.scheduling.machine.mapper.MachineTypeMapper;
import com.scheduling.machine.service.MachineTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 机器类型业务层实现类
 *
 * @author 开发团队
 * @since 2025-05-29
 */
@Slf4j
@Service
public class MachineTypeServiceImpl extends ServiceImpl<MachineTypeMapper, MachineType> implements MachineTypeService {

    @Autowired
    private MachineMapper machineMapper;

    @Override
    public IPage<MachineType> getMachineTypePage(MachineTypeQueryDTO queryDTO) {
        Page<MachineType> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        return baseMapper.selectMachineTypePage(page, queryDTO);
    }

    @Override
    public MachineType getMachineTypeById(String machineTypeId) {
        if (StrUtil.isBlank(machineTypeId)) {
            throw new RuntimeException("机器类型ID不能为空");
        }
        return baseMapper.selectById(machineTypeId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addMachineType(MachineTypeDTO machineTypeDTO) {
        // 检查机器类型名称是否已存在
        if (checkTypeNameExists(machineTypeDTO.getTypeName(), null)) {
            throw new RuntimeException("机器类型名称已存在");
        }

        // 生成机器类型ID
        if (machineTypeDTO.getMachineTypeId() == null || machineTypeDTO.getMachineTypeId().isEmpty()) {
            Integer maxId = baseMapper.selectMaxMachineTypeNumber();
            int nextNum = (maxId != null) ? maxId + 1 : 1;
            String newId = String.format("MT%03d", nextNum);
            machineTypeDTO.setMachineTypeId(newId);
        }

        MachineType machineType = new MachineType();
        BeanUtil.copyProperties(machineTypeDTO, machineType);

        int result = baseMapper.insert(machineType);
        if (result > 0) {
            log.info("添加机器类型成功，机器类型ID：{}", machineType.getMachineTypeId());
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMachineType(MachineTypeDTO machineTypeDTO) {
        if (StrUtil.isBlank(machineTypeDTO.getMachineTypeId())) {
            throw new RuntimeException("机器类型ID不能为空");
        }

        // 检查机器类型是否存在
        MachineType existMachineType = baseMapper.selectById(machineTypeDTO.getMachineTypeId());
        if (existMachineType == null) {
            throw new RuntimeException("机器类型不存在");
        }

        // 检查机器类型名称是否已存在（排除当前机器类型）
        if (checkTypeNameExists(machineTypeDTO.getTypeName(), machineTypeDTO.getMachineTypeId())) {
            throw new RuntimeException("机器类型名称已存在");
        }

        MachineType machineType = new MachineType();
        BeanUtil.copyProperties(machineTypeDTO, machineType);

        int result = baseMapper.updateById(machineType);
        if (result > 0) {
            log.info("更新机器类型成功，机器类型ID：{}", machineType.getMachineTypeId());
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMachineType(String machineTypeId) {
        if (StrUtil.isBlank(machineTypeId)) {
            throw new RuntimeException("机器类型ID不能为空");
        }

        // 检查机器类型是否存在
        MachineType machineType = baseMapper.selectById(machineTypeId);
        if (machineType == null) {
            throw new RuntimeException("机器类型不存在");
        }

        // 检查是否有机器在使用该类型
        Integer machineCount = machineMapper.countByMachineTypeId(machineTypeId);
        if (machineCount != null && machineCount > 0) {
            throw new RuntimeException("该机器类型下还有机器，无法删除");
        }

        int result = baseMapper.deleteById(machineTypeId);
        if (result > 0) {
            log.info("删除机器类型成功，机器类型ID：{}", machineTypeId);
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMachineTypes(List<String> machineTypeIds) {
        if (machineTypeIds == null || machineTypeIds.isEmpty()) {
            throw new RuntimeException("机器类型ID列表不能为空");
        }

        for (String machineTypeId : machineTypeIds) {
            deleteMachineType(machineTypeId);
        }
        return true;
    }

    @Override
    public List<MachineType> getAllMachineTypes() {
        LambdaQueryWrapper<MachineType> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(
                MachineType::getMachineTypeId,
                MachineType::getTypeName,
                MachineType::getDescription,
                MachineType::getCreateTime
        );
        wrapper.orderByAsc(MachineType::getTypeName);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public boolean checkTypeNameExists(String typeName, String excludeId) {
        if (StrUtil.isBlank(typeName)) {
            return false;
        }
        Integer count = baseMapper.checkTypeNameExists(typeName, excludeId);
        return count != null && count > 0;
    }
} 